function buildTree(data) {
    let map = {};
    let result = [];
    data.forEach(item => {
      map[item.id] = { ...item, children: [] };
    });
    Object.values(map).forEach(item => {
      if (!item.parentId) {
        result.push(item);
      } else {
        map[item.parentId].children.push(item);
      }
    });
    return result;
  }
  
  const arr = [
    { id: 1, parentId: null },
    { id: 2, parentId: 1 },
    { id: 3, parentId: 1 },
    { id: 4, parentId: 2 },
    { id: 5, parentId: 2 },
    { id: 6, parentId: 3 },
  ];
  
  let tree = buildTree(arr);
  console.log(tree);